package com.idealighter.game.games.fqzs.handler;

import com.idealighter.game.core.annotation.ResMsgHandler;
import com.idealighter.game.games.fqzs.SharkPlayer;
import com.idealighter.game.games.fqzs.message.ReqCancelApplyBankerMsg;
import com.idealighter.game.games.fqzs.message.ResApplyBankersMsg;
import com.idealighter.game.message.ModuleMsgIdConstant;
import com.idealighter.game.message.core.ResMessage;
import com.idealighter.game.robot.context.ApplicationContext;
import com.idealighter.game.robot.core.Player;
import com.idealighter.game.robot.handler.ResMessageHandler;
import com.idealighter.game.robot.scheduler.PlayerScheduler;
import com.idealighter.utils.code.RandCodeUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


@ResMsgHandler(ModuleMsgIdConstant.Fqzs.RES_APPLY_BANKER)
public class ResApplyBankersHandler implements ResMessageHandler {

  // private static final Logger LOG = LoggerFactory.getLogger(ResApplyBankersHandler.class);
  // 取消上庄概率(x/100)
  public static int CANCAL_APPLY_BANKER_ROB = 20;

  @Override
  public void action(Player player, ResMessage message) {
    ResApplyBankersMsg msg = (ResApplyBankersMsg) message;
    List<Long> list = msg.getApplicants();
    List<Long> oldList = new ArrayList<Long>(player.applyBankers);

    player.applyBankers.clear();
    player.applyBankers.addAll(list);

    // 上庄人数控制（取消上庄）
    int robotApplyNums = robotApplyBankers(list);
    // 判断是否原先就在申请列表，如果在，就取消上庄
    if (oldList.contains(player.playerId) && list.contains(player.playerId)) {
      SharkPlayer sharkPlayer = (SharkPlayer) player;
      if (robotApplyNums > sharkPlayer.maxRobotApplyBankers) {
        // 取消申请上庄
        player.schedule(() -> cancelApplyBanker(player), RandCodeUtil.random(0, 10),
            TimeUnit.SECONDS);
      }
    }
  }

  private void cancelApplyBanker(Player player) {
    int rand = RandCodeUtil.random(100);
    if (rand <= CANCAL_APPLY_BANKER_ROB) {
      ReqCancelApplyBankerMsg msg = new ReqCancelApplyBankerMsg();
      player.sendMsg(msg);
    }
  }

  private int robotApplyBankers(List<Long> applys) {
    PlayerScheduler playerScheduler = ApplicationContext.getBean(PlayerScheduler.class);
    int result = 0;
    if (applys != null) {
      for (Long apply : applys) {
        if (playerScheduler.isRobot(apply)) {
          result += 1;
        }
      }
    }
    return result;
  }
}
